package smtpserver

import (
	"bufio"
	"fmt"
	"os"
	"time"
)

// Message 表示一封完整的邮件
type Message struct {
	From      string
	To        []string
	Data      []byte
	Date      time.Time
	MessageID string
}

// 保存邮件到文件
func (m *Message) SaveToFile() error {
	// 创建存储目录（如果不存在）
	if _, err := os.Stat("received_mails"); os.IsNotExist(err) {
		if err := os.Mkdir("received_mails", 0755); err != nil {
			return err
		}
	}

	// 生成唯一文件名
	filename := fmt.Sprintf("received_mails/%s.eml", time.Now().Format("20060102150405"))

	// 创建文件
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()

	// 写入邮件头部
	writer := bufio.NewWriter(file)
	writer.WriteString(fmt.Sprintf("From: %s\r\n", m.From))
	writer.WriteString("To: ")
	for i, recipient := range m.To {
		if i > 0 {
			writer.WriteString(", ")
		}
		writer.WriteString(recipient)
	}
	writer.WriteString("\r\n")
	writer.WriteString(fmt.Sprintf("Date: %s\r\n", m.Date.Format(time.RFC1123Z)))
	writer.WriteString(fmt.Sprintf("Message-ID: <%s@localhost>\r\n", time.Now().Format("20060102150405")))

	// 写入邮件正文
	writer.WriteString("\r\n")
	writer.Write(m.Data)

	return writer.Flush()
}
